<template>
  <div class="flexContent">
    <!-- 采购订单 -->
    <div class="searchBox">
      <el-form ref="form" :model="form" label-position="left" label-width="auto">
        <div class="serFlexBox">
          <div class="inputBox">
            <el-row :gutter="12" style="display: flex;flex-wrap: wrap;">
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="门店">
                  <el-select @click.native="getShopEasy" v-model="form.storeId" placeholder="请选择门店" style="width: 95%;"
                    filterable clearable popper-class="eloption" @change="changeShop">
                    <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="商品">
                  <el-input v-clearEmoji v-model.trim="form.name" style="width: 95%;" clearable
                    placeholder="请输入商品名称、条码、助记符" @keyup.enter.native="searchFn" @clear="resetForm" />
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="订单编号">
                  <el-input v-clearEmoji v-model.trim="form.orderNum" style="width: 95%;" clearable
                    placeholder="请输入订单编号" @keyup.enter.native="searchFn" @clear="resetForm" />
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="商品类型">
                  <el-select @change="changeGoodsType" v-model="type" style="width: 95%;" placeholder="请选择商品类型">
                    <el-option value="0" label="标品" />
                    <el-option value="1" label="非标品" />
                    <el-option value="2" label="自营" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="10" :xl="6">
                <el-form-item label="付款时间">
                  <el-date-picker v-model="date" clearable type="daterange" unlink-panels range-separator="-"
                    start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" style="width: 95%;" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="btnBox">
            <el-button @click.stop="searchFn" class="searchBtn" icon="el-icon-search">搜索</el-button>
            <el-button @click.stop="resetForm('form')" class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <div class="add">
      <el-button class="addBtn" @click="exportSell" v-has="'procure_add'">导出</el-button>
    </div>
    <div class="table" id="tableBox" v-height>
      <div style="flex:1;" v-show="type == '0'">
        <vxe-table :column-config="{ resizable: true }" border class="tablebox" ref="xTable1"
          :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%" height="100%"
          size="medium" align="center">
          <vxe-column type="seq" title="序号" width="80" />
          <vxe-column field="storeName" title="门店名称" :min-width="elTableAdaptationWidth('storeName', tableData)" />
          <vxe-column field="orderNum" title="订单编号" :min-width="elTableAdaptationWidth('orderNum', tableData)" />
          <vxe-column field="firstCode" title="商品条码" :min-width="elTableAdaptationWidth('firstCode', tableData)" />
          <vxe-column field="name" title="商品名称" :min-width="elTableAdaptationWidth('name', tableData)" />
          <vxe-column field="commodityNum" title="销售数量" min-width="100" />
          <vxe-column field="specNumber" title="规格数量" min-width="100" />
          <vxe-column field="standard" title="规格" min-width="100" />
          <vxe-column field="receivableAmount" title="售卖金额（元）" min-width="150" />
          <vxe-column field="receiptsAmount" title="实收金额（元）" min-width="150" />
          <vxe-column field="payTime" title="付款时间" min-width="150">
            <template v-slot="{ row }">
              <div>
                {{ row.payTime | parseTime }}
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div style="flex:1;" v-show="type == '1'">
        <vxe-table :column-config="{ resizable: true }" border class="tablebox" ref="xTable2"
          :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%" height="100%"
          size="medium" align="center">
          <vxe-column type="seq" title="序号" width="80" />
          <vxe-column field="storeName" title="门店名称" :min-width="elTableAdaptationWidth('storeName', tableData)" />
          <vxe-column field="orderNum" title="订单编号" :min-width="elTableAdaptationWidth('orderNum', tableData)" />
          <vxe-column field="name" title="商品名称" :min-width="elTableAdaptationWidth('name', tableData)" />
          <vxe-column field="weight" title="重量（KG）" min-width="150" />
          <vxe-column field="storePrice" title="零售价（元）" min-width="150" />
          <vxe-column field="receivableAmount" title="售卖金额（元）" min-width="150" />
          <vxe-column field="receiptsAmount" title="实收金额（元）" min-width="150" />
          <vxe-column field="payTime" title="付款时间" min-width="150">
            <template v-slot="{ row }">
              <div>
                {{ row.payTime | parseTime }}
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div style="flex:1;" v-show="type == '2'">
        <vxe-table :column-config="{ resizable: true }" border class="tablebox" ref="xTable3"
          :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%" height="100%"
          size="medium" align="center">
          <vxe-column type="seq" title="序号" width="80" />
          <vxe-column field="storeName" title="门店名称" :min-width="elTableAdaptationWidth('storeName', tableData)" />
          <vxe-column field="orderNum" title="订单编号" :min-width="elTableAdaptationWidth('orderNum', tableData)" />
          <vxe-column field="firstCode" title="商品条码" :min-width="elTableAdaptationWidth('firstCode', tableData)" />
          <vxe-column field="name" title="商品名称" :min-width="elTableAdaptationWidth('name', tableData)" />
          <vxe-column field="commodityNum" title="销售数量" min-width="100" />
          <vxe-column field="storePrice" title="零售价（元）" min-width="150" />
          <vxe-column field="receivableAmount" title="售卖金额（元）" min-width="150" />
          <vxe-column field="receiptsAmount" title="实收金额（元）" min-width="150" />
          <vxe-column field="payTime" title="付款时间" min-width="150">
            <template v-slot="{ row }" >
              <div>
                {{ row.payTime | parseTime }}
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="paginationBox">
        <el-pagination :current-page.sync="page.pageNum" background :page-sizes="$pageSizes"
          :page-size.sync="page.pageSize" layout="total,->, sizes, prev, pager, next, jumper" :total="page.total"
          @size-change="changePageSize" @current-change="getSaleReportList" />
      </div>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import { getSaleReportList, exportSell } from "@/api/report";
import { getShopEasy } from '@/api/shop';
export default {
  name: "SellReport",
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      storeList: [],

      date: [],
      form: {
        name: "",
        storeId: "",
        orderNum: ""
      },

      tableData: [],
      isSearch: false,

      type: '0',
    };
  },
  computed: {
    minDate() {
      if (this.date == null) {
        return "";
      }
      if (this.date.length > 0) {
        return this.date[0];
      } else {
        return "";
      }
    },
    maxDate() {
      if (this.date == null) {
        return "";
      }
      if (this.date.length > 0) {
        return this.date[1];
      } else {
        return "";
      }
    },
  },
  mounted() {
    this.getSaleReportList();
  },
  methods: {
    async getShopEasy() {
      let res = await getShopEasy();
      if (res.code === 200) {
        this.storeList = res.data.store;
      }
    },
    async getSaleReportList() {
      let { name, storeId, orderNum } = this.form;
      let { maxDate, minDate } = this;
      let { pageNum, pageSize } = this.page;
      if (!this.isSearch) {
        maxDate = '';
        maxDate = '';
        name = '';
        orderNum = '';
      }
      let reqObj = { name, storeId, pageNum, pageSize, minDate, maxDate,type: this.type,orderNum };
      let res = await getSaleReportList(reqObj);
      if (res.code === 200) {
        this.tableData = res.data.list;
        let $table = null;
        if(this.type == '0'){
          $table = this.$refs.xTable1
        }else if(this.type == '1'){
          $table = this.$refs.xTable2
        }else {
          $table = this.$refs.xTable3
        }
        $table.loadData(this.tableData);
        this.page.total = res.data.total;
      }
    },
    searchFn() {
      this.page.pageNum = 1;
      this.isSearch = true;
      this.getSaleReportList();
    },
    resetForm() {
      this.page.pageNum = 1;
      this.page.pageSize = 20;
      this.isSearch = false;
      this.form = {
        name: "",
        storeId: "",
        orderNum: ""
      };
      this.date = [];
      this.getSaleReportList();
    },
    // 修改每页几条
    changePageSize() {
      this.page.pageNum = 1;
      this.getSaleReportList();
    },
    exportSell() {
      this.$confirm(`确认导出数据吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let { name, storeId, orderNum } = this.form;
        let { maxDate, minDate } = this;
        let reqObj = { name, storeId, minDate, maxDate ,type:this.type, orderNum};
        let response = await exportSell(reqObj);
        let res = null;
        if (response.data.type === "application/json") {
          const reader = new FileReader();  //创建一个FileReader实例
          reader.readAsText(response.data, 'utf-8'); //读取文件,结果用字符串形式表示
          reader.onload = () => {//读取完成后,**获取reader.result**
            res = JSON.parse(reader.result)
            if (res.code !== 200) {
              this.$message.error(res.message);
              return;
            }
          }
        } else {
          const fileName = decodeURIComponent(response.headers["content-disposition"].split(";")[1].split("''")[1]);
          FileSaver.saveAs(response.data, fileName);
        }
      })
    },

    // 切换门店类型
    changeGoodsType() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      }
      this.getSaleReportList();
    },
    changeShop(){
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      }
      this.getSaleReportList();
    }
  },
};
</script>

<style lang="scss" scoped></style>
